package com.ms.exmaple.orm.service;

import com.ms.exmaple.orm.entity.User;
import com.ms.exmaple.orm.mapper.UserMapper;
import com.ms.orm.annotation.Param;
import com.ms.orm.dboperator.service.BaseService;
import com.ms.orm.meta.IPage;
import com.ms.orm.meta.SqlAndParams;
import com.ms.orm.util.SqlGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;

/**
 * @author .
 * DefaultBaseService 中的方法如果需要事务，子类需要覆盖其对应方法
 * 需要开启 基于 Ciglib 的代理，
 * @EnableAspectJAutoProxy(proxyTargetClass=true)
 * 如果不开启 proxyTargetClass = true,生成的代理类是 'com.sun.proxy.$Proxy25'，无法转换为 UserService类型
 *
 */
@Service
public class UserService extends BaseService<User> {


    private UserMapper userMapper;

    @Autowired
    public UserService(@Qualifier("userMapper")UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Override
    public List<User> findAll() {
        return super.findAll();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(User entity) {
        // 构建SQL语句并执行保存操作
        SqlAndParams sqlAndParams = SqlGenerator.generateInsertSql(entity);
        return jdbcTemplate.update(sqlAndParams.getSql(), sqlAndParams.getParams().toArray());
        //throw new RuntimeException("Could not save user data");
    }

    public List<User> selectUsersWithConditions(String name,Integer age){
        return userMapper.selectUsersWithConditions(name, age);
    }

    public IPage<User> selectUsersWithConditionPage(IPage<User> page,String name, Integer age){
        return userMapper.selectUsersWithConditionPage(page,name, age);
    }

}
